//
//  Merge_MineAndFavor_Manager.m
//  KidReading
//
//  Created by YangShuai on 17/2/20.
//  Copyright © 2017年 刘赞黄Telen. All rights reserved.
//

#import "Merge_MineAndFavor_Manager.h"
#import "ConstDefine.h"
@interface Merge_MineAndFavor_Manager (){
    BOOL _firstRequestCom_mine;
    BOOL _firstRequestCom_favor;
    NSArray* _favorBooksIdArray;
}

@end

@implementation Merge_MineAndFavor_Manager
static Merge_MineAndFavor_Manager *singleManager = nil;
+(Merge_MineAndFavor_Manager*)defaultManager{
    if (singleManager == nil) {
        @synchronized (self) {
            singleManager = [[Merge_MineAndFavor_Manager alloc] init];
        }
    }
    return singleManager;
}

-(instancetype)init{
    self = [super init];
    if (self) {
        
    }
    return self;
}

//只获取我的图书或我的收藏缓存(按照最近阅读时间排序)
-(void)getBooksWithMergeType:(MergeType)mergeType Success:(void(^)(NSArray * retArray))success{
    UserInfo* uinfo = [CacheData shareSingle].getUserLoginInfo;
    [[DBHelper shareInstance] Merge_MineAndFavor_getDictList:^(NSArray *list) {
        NSArray* bookList = [self bookModelFromDBList:list];
        NSMutableArray* bookIdsArray = [NSMutableArray new];
        for (TABLE_BOOKS* bookModal in bookList) {
            [bookIdsArray addObject:@(bookModal.bookId)];
        }
        //
        NSMutableArray* bookList_mu = [NSMutableArray arrayWithArray:bookList];
        //
        [[DBHelper shareInstance] Merge_MineAndFavor_getDictList:^(NSArray *tempList) {
            NSMutableArray* addArray = [NSMutableArray new];
            NSMutableArray* minusArray = [NSMutableArray new];
            for (NSDictionary* bookDict in tempList) {
                if ([bookDict[@"tempType"] integerValue] == TempType_ADD) {
                    [addArray addObject:bookDict];
                }else if ([bookDict[@"tempType"] integerValue] == TempType_MINUS ){
                    [minusArray addObject:bookDict];
                }
            }
            NSArray* bookList_temp_add = [self bookModelFromDBList:addArray];
            NSArray* bookList_temp_minus = [self bookModelFromDBList:minusArray];
            for (TABLE_BOOKS* bookModal_temp_add in bookList_temp_add) {
                if ([bookIdsArray containsObject:@(bookModal_temp_add.bookId)]) {
                    [bookList_mu removeObjectAtIndex:[bookIdsArray indexOfObject:@(bookModal_temp_add.bookId)]];
                    [bookIdsArray removeObject:@(bookModal_temp_add.bookId)];
                }
                [bookList_mu addObject:bookModal_temp_add];
                [bookIdsArray addObject:@(bookModal_temp_add.bookId)];
            }
            for (TABLE_BOOKS* bookModal_temp_minus in bookList_temp_minus) {
                if ([bookIdsArray containsObject:@(bookModal_temp_minus.bookId)]) {
                    [bookList_mu removeObjectAtIndex:[bookIdsArray indexOfObject:@(bookModal_temp_minus.bookId)]];
                    [bookIdsArray removeObject:@(bookModal_temp_minus.bookId)];
                }
            }
            //
            if (mergeType == MergeType_Favor) {
                _favorBooksIdArray = bookIdsArray;
            }
            //
            if (mergeType == MergeType_Audio) {
                NSSortDescriptor *sortByA = [NSSortDescriptor sortDescriptorWithKey:@"lastModifyDate" ascending:YES];//升序
                [bookList_mu sortUsingDescriptors:@[sortByA]];
                [[DBHelper shareInstance] Merge_MineAndFavor_getAudioSortCompleted:^(NSString *sortStr) {
                    if (sortStr.length) {
                        [[DBHelper shareInstance] tbbooks_mutableArray:bookList_mu orderBy_BookIds:sortStr];
                    }
                    if (success) success(bookList_mu);
                }];
            }else{
                NSSortDescriptor *sortByA = [NSSortDescriptor sortDescriptorWithKey:@"lastModifyDate" ascending:NO];//降序
                [bookList_mu sortUsingDescriptors:@[sortByA]];
                if (success) success(bookList_mu);
            }
        } WithIsTempTable:YES where:[NSString stringWithFormat:@"where userId = %@ and mergeType = '%@'",@(uinfo.uid),@(mergeType)]];
    } WithIsTempTable:NO where:[NSString stringWithFormat:@"where userId = %@ and mergeType = '%@'",@(uinfo.uid),@(mergeType)]];
}
//

//合并我的图书或者我的收藏
-(void)myBookManagerMergeMineOrMergeFavorWithWithMergeType:(MergeType)mergeType UpdateArray:(NSArray*)updateArray DeleteArray:(NSArray*)deleteArray Success:(void (^)(NSArray * retArray))success failure:(void (^)(NSError *error))failure{
    [[DBHelper shareInstance] Merge_MineAndFavor_getUserMergeTimestampWithMergeType:mergeType Completed:^(long long timestamp) {
        if (![[NetRequestLimiter defaultLimiter] isOneDayLimitedWithCacheTimestamp:timestamp]) {
            timestamp = 0;
        }
        UserInfo* uinfo = [CacheData shareSingle].getUserLoginInfo;
        [[NetGetPostsWithCache shareInstance] mergeMineWithData_timestamp:timestamp MergeType:mergeType UpdateArray:updateArray DeleteArray:deleteArray Success:^(NSDictionary *retDict) {
            //服务器时间
            LongLong server_timestamp = [retDict[@"server_timestamp"] longLongValue];
            [[DBHelper shareInstance] Merge_MineAndFavor_updateMergeTimestampWithNewTimestamp:server_timestamp MergeType:mergeType completed:nil];
            //
            NSDictionary* deleteBooksDict = retDict[@"delete"];
            NSString* deleteBookIds = deleteBooksDict[@"bookIds"];
            NSArray* deleteBookIdArray = [deleteBookIds componentsSeparatedByString:@","];
            NSMutableArray* deleteDictArr = [NSMutableArray new];
            for (NSString* deleteBookId in deleteBookIdArray) {
                if ([deleteBookId integerValue] > 0) {
                    NSDictionary* deleteDict = @{@"userId":@(uinfo.uid),@"mergeType":@(mergeType),@"bookId":@([deleteBookId integerValue])};
                    [deleteDictArr addObject:deleteDict];
                }
            }
            //
            NSDictionary* updateBooksDict = retDict[@"update"];
            NSString* updateBookIds = updateBooksDict[@"bookIds"];
            NSDictionary* updateBookSubs = updateBooksDict[@"bookSub"];
            //删除需要删除的数据
            [[DBHelper shareInstance] Merge_MineAndFavor_deletListWithIsTempTable:NO dictArr:deleteDictArr complete:^{
                //添加新的数据
                NSMutableArray *allBooksModelArray = [NSMutableArray new];
                [[DBHelper shareInstance] selectBookWithReadCountList_Books:updateBookIds complete:^(NSDictionary *reDict) {
                    NSArray *bookModelArray = reDict[@"book"];
                    for (TABLE_BOOKS* bookModel in bookModelArray) {
                        NSString* bookKey = [NSString stringWithFormat:@"%ld",(long)bookModel.bookId];
                        NSDictionary *bookSubDict = updateBookSubs[bookKey];
                        //
                        [RootViewController mergeBookSubWithBaseBookTable:bookModel BookSub:bookSubDict];
                        NSString* bookModalStr = [[bookModel JRMJ_keyValues] JRMJ_JSONString];
                        [allBooksModelArray addObject:@{@"userId":@(uinfo.uid),@"bookId":@(bookModel.bookId),@"mergeType":@(mergeType),@"bookInfoStr":bookModalStr}];
                    }
                    [[DBHelper shareInstance] Merge_MineAndFavor_updateListWithIsTempTable:NO dictArr:allBooksModelArray complete:^{
                        [self getBooksWithMergeType:mergeType Success:^(NSArray *retArray) {
                            if (success) success(retArray);
                            if (mergeType == MergeType_Mine) {
                                _firstRequestCom_mine = YES;
                            }else if (mergeType == MergeType_Favor){
                                _firstRequestCom_favor = YES;
                            }
                        }];
                    }];
                }];
            }];
        } failure:^(NSError *error) {
            if (failure) {
                failure(error);
            }
        }];
    }];
}
//将数据库查出格式转化为bookModel的数组
-(NSArray<TABLE_BOOKS*>*)bookModelFromDBList:(NSArray*)dbList{
    NSMutableArray* bookModalArray = [NSMutableArray new];
    for (NSDictionary* dbDict in dbList) {
        NSString* bookModelStr = dbDict[@"bookInfoStr"];
        TABLE_BOOKS* bookModel = [TABLE_BOOKS JRMJ_objectWithKeyValues:bookModelStr.JRMJ_JSONObject];
        [bookModalArray addObject:bookModel];
    }
    return bookModalArray;
}
//获取我的图书或我的收藏前?本
-(void)getBooksWithMergeType:(MergeType)mergeType MorethenBookCount:(NSInteger)bookCount Success:(void (^)(NSArray * retArray))success failure:(void (^)(NSError *error))failure cache:(void (^)(NSArray * cacheRetArray))cacheBack{
    [self getBooksWithMergeType:mergeType Success:^(NSArray *retArray) {
        NSArray *bookArray = [self getMoreThenBookWithCount:bookCount TotleBooksArray:retArray];
        if (cacheBack) cacheBack(bookArray);
    }];
    if (!_firstRequestCom_mine && !_firstRequestCom_favor) {
        [self myBookManagerMergeMineOrMergeFavorWithWithMergeType:mergeType UpdateArray:@[] DeleteArray:@[] Success:^(NSArray *retArray) {
            NSArray *bookArray = [self getMoreThenBookWithCount:bookCount TotleBooksArray:retArray];
            if (success) success(bookArray);
            //同步完我的图书,同步
            if (MergeType_Mine) {
                [self audioListRequest];
            }
        } failure:^(NSError *error) {
            if (failure) failure(error);
        }];
    }
}
//应用第一次启动同步播放列表
-(void)audioListRequest{
    [self myBookManagerMergeMineOrMergeFavorWithWithMergeType:MergeType_Audio UpdateArray:@[] DeleteArray:@[] Success:^(NSArray *retArray) {
        [[RootViewController shareLastInstance] initialJRAdudioData];
    } failure:nil];
}



-(NSArray*)getMoreThenBookWithCount:(NSInteger)bookCount TotleBooksArray:(NSArray*)booksArray{
    NSMutableArray* retArray_mu = [NSMutableArray arrayWithArray:booksArray];
    NSSortDescriptor *sortByA = [NSSortDescriptor sortDescriptorWithKey:@"lastModifyDate" ascending:NO];//降序
    [retArray_mu sortUsingDescriptors:@[sortByA]];
    NSArray* bookArray = @[];
    if (booksArray.count > bookCount) {
        bookArray = [retArray_mu subarrayWithRange:NSMakeRange(0, bookCount)];
    }else{
        bookArray = retArray_mu;
    }
    return bookArray;
}

//切换账户重新获取数据
-(void)resetFirstRequestCompleted{
    _firstRequestCom_mine = NO;
    _firstRequestCom_favor = NO;
}
//删除或者添加先进入缓存表
-(void)updateTempTableWithBookModel:(TABLE_BOOKS*)bookModal WithTempType:(TempType)tempType MergeType:(MergeType)mergeType Completed:(void(^)())comp{
    UserInfo* uinfo = [CacheData shareSingle].getUserLoginInfo;
    bookModal.infoDefine = nil;
    NSString* bookModalStr = [[bookModal JRMJ_keyValues] JRMJ_JSONString];
    NSDictionary* dict = @{@"userId":@(uinfo.uid),@"bookId":@(bookModal.bookId),@"mergeType":@(mergeType),@"tempType":@(tempType),@"bookInfoStr":bookModalStr};
    [[DBHelper shareInstance] Merge_MineAndFavor_getList:^(NSArray *list) {
        for (TABLE_BOOKS_MergeMineANDFavor_TEMP* bookTemp in list) {
            if (tempType == TempType_ADD) {
                if (bookTemp.bookId == bookModal.bookId && bookTemp.tempType == TempType_MINUS) {
                    [[DBHelper shareInstance] Merge_MineAndFavor_deletListWithIsTempTable:YES tbArr:[self sqlListToDeletedList:@[bookTemp]] complete:^{
                        if (comp) comp();
                    }];
                    return;
                }
            }else if (tempType == TempType_MINUS){
                if (bookTemp.bookId == bookModal.bookId && bookTemp.tempType == TempType_ADD) {
                    [[DBHelper shareInstance] Merge_MineAndFavor_deletListWithIsTempTable:YES tbArr:[self sqlListToDeletedList:@[bookTemp]] complete:^{
                        if (comp) comp();
                    }];
                    return;
                }
            }
        }
        [[DBHelper shareInstance] Merge_MineAndFavor_updateListWithIsTempTable:YES dictArr:@[dict] complete:^{
            if (comp) comp();
        }];
    } WithIsTempTable:YES where:[NSString stringWithFormat:@"where userId = '%@' and mergeType = '%@'",@(uinfo.uid),@(mergeType)]];
}

//同步缓存表中的数据
-(void)synchronousBooksDataWithNetWithMergeType:(MergeType)mergeType{
    UserInfo* uinfo = [CacheData shareSingle].getUserLoginInfo;
    [[DBHelper shareInstance] Merge_MineAndFavor_getList:^(NSArray *list) {
        if (list.count) {
            [self checkSqlListToParamsWithList:list Completed:^(NSArray *deletedArray, NSArray *updatedArray) {
                [self myBookManagerMergeMineOrMergeFavorWithWithMergeType:mergeType UpdateArray:updatedArray DeleteArray:deletedArray Success:^(NSArray *retArray) {
                    [[DBHelper shareInstance] Merge_MineAndFavor_deletListWithIsTempTable:YES tbArr:[self sqlListToDeletedList:list] complete:^{
                        [DataProcess do_Main_quick:^{
                            [[RootViewController shareLastInstance] refreshBookHouseIsMine:YES];
                        }];
                    }];
                } failure:^(NSError *error) {
                    [DataProcess do_Main_quick:^{
                        [[RootViewController shareLastInstance] refreshBookHouseIsMine:YES];
                    }];
                }];
            }];
        }else{
            [DataProcess do_Main_quick:^{
                [[RootViewController shareLastInstance] refreshBookHouseIsMine:YES];
            }];
        }
    } WithIsTempTable:YES where:[NSString stringWithFormat:@"where userId = '%@' and mergeType = '%@'",@(uinfo.uid),@(mergeType)]];
    
}

//同步本地图书顺序
-(void)updateAudioListSortWithSortStr:(NSString*)sortStr{
    [[DBHelper shareInstance] Merge_MineAndFavor_updateAudioSortWithSortStr:sortStr completed:nil];
}

//将数据库查询出的缓存数据解析为简单的数据
-(NSArray*)sqlListToDeletedList:(NSArray*)list{
    NSMutableArray* deleteList = [NSMutableArray new];
    for (TABLE_BOOKS_MergeMineANDFavor_TEMP* bookTemp in list) {
        bookTemp.bookInfoStr = nil;
        [deleteList addObject:bookTemp];
    }
    return deleteList;
}
//同步数据时将数据库查出的数据解析为需要的参数格式
-(void)checkSqlListToParamsWithList:(NSArray*)list Completed:(void(^)(NSArray* deletedArray, NSArray* updatedArray))comp{
    NSMutableArray* deletedArray = [NSMutableArray new];
    NSMutableArray* updatedArray = [NSMutableArray new];
    for (TABLE_BOOKS_MergeMineANDFavor_TEMP* bookTemp in list) {
        TABLE_BOOKS* bookModel = [TABLE_BOOKS JRMJ_objectWithKeyValues:bookTemp.bookInfoStr.JRMJ_JSONObject];
        if (bookTemp.tempType == TempType_ADD) {
            [updatedArray addObject:@{@"bookId":@(bookModel.bookId),@"bsId":@(bookModel.itemId),@"createDate":@(bookModel.lastModifyDate),@"lastModifyDate":@(bookModel.lastModifyDate)}];
        }else if (bookTemp.tempType == TempType_MINUS){
            [deletedArray addObject:@{@"bookId":@(bookModel.bookId)}];
        }
    }
    if (comp) comp(deletedArray,updatedArray);
}

//判断一本书是否被收藏
-(BOOL)isFavorWithBookId:(NSInteger)bookId{
    if ([_favorBooksIdArray containsObject:@(bookId)]) {
        return YES;
    }
    return NO;
}


@end
